﻿using System;
using System.Xml;

using Yawf.Core.Utils;
using Yawf.Core.Xml;

namespace Yawf.Web.Managers.Entities {
	public class View {
		private bool downloadable = false;
		private String contentType = "text/html";
		private String extension = "";
		private String resource = "";
		private String encoding = "utf-8";
		private String content = "";

		public bool Downloadable { get { return downloadable; } set { downloadable = value;} }
		public String ContentType { get { return contentType; } set { contentType = value; } }
		public String Extension { get { return extension; } set { extension = value; } }
		public String Resource { get { return resource; } set { resource = value; } }
		public String Encoding { get { return encoding; } set { encoding = value; } }
		public String Content { get { return content; } set { content = value; } }

		/// <summary>
		/// Gets the name of the resource,removing extension and
		/// removing ~/ character
		/// </summary>
		/// <returns></returns>
		public String GetResourceName() {
			String tmpName;
			int dotIndex;

			tmpName = Resource;
			if (tmpName != null) {
				if (tmpName.StartsWith("~/")) {
					tmpName = tmpName.Substring(2);
				}
				dotIndex = tmpName.LastIndexOf('.');
				if (dotIndex > -1) {
					tmpName = tmpName.Substring(0,dotIndex);
				}
			} else {
				tmpName = "defaultName";
			}

			return tmpName;
		}					// tmpName

		/// <summary>
		/// Constructor with resource, reads resource XML and gets View data 
		/// from XML
		/// </summary>
		/// <param name="resourcePath">Path to resource</param>
		public View(String resourcePath) {
			XmlDocument xmlDoc;
			XmlNode xmlNode;
			XmlElement tmpElem;
			String tmpStr;
		
			// Sets the resource path
			Resource = resourcePath;

			xmlDoc = XmlUtils.ReadXmlDocument(resourcePath);
			if (xmlDoc != null && xmlDoc.DocumentElement != null) {
				xmlNode = xmlDoc.DocumentElement.SelectSingleNode("view");
				if (xmlNode is XmlElement) {
					tmpElem = (XmlElement)xmlNode;

					// Get content type
					tmpStr = tmpElem.GetAttribute("content-type");
					if (tmpStr != null && tmpStr.Trim() != "") {
						ContentType = tmpStr;
					}

					tmpStr = tmpElem.GetAttribute("extension");
					if (tmpStr != null && tmpStr.Trim() != "") {
						Extension = tmpStr;
					}

					tmpStr = tmpElem.GetAttribute("encoding");
					if (tmpStr != null && tmpStr.Trim() != "") {
						Encoding = tmpStr;
					} else {
						Encoding = "utf-8";
					}

					// Get if downloadable
					tmpStr = tmpElem.GetAttribute("downloadable");
					Downloadable = StringUtils.BoolValue(tmpStr);

					Content = tmpElem.InnerXml;
				}
			}
		}
	}
}
